package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    /**
     * 添加菜品
     * @param dishDTO
     */
    @Override
    public void addDish(DishDTO dishDTO) {//添加菜品  还要完善口味
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        if (dishDTO.getStatus()==null){
            dish.setStatus(0);
        }
        dishMapper.addDish(dish);

        //拿到插入菜品的id
        Long dishId = dish.getId();
        //拿到其口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors.size()==0){
            return;
        }else {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
                dishFlavorMapper.insert(flavor);
            });

        }
    }


    /**
     * 自己写的分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult getDishPage(DishPageQueryDTO dishPageQueryDTO) {
        long start = System.currentTimeMillis();


        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<Dish> dishLists=dishMapper.queryPageList(dishPageQueryDTO);
        Page<DishVO> p=new Page<>();
        dishLists.forEach(new Consumer<Dish>() {
            @Override
            public void accept(Dish dish) {
                DishVO DishVO = new DishVO();
                BeanUtils.copyProperties(dish,DishVO);
                //根据dish里面的categoryId值查找到对应的分类名称
                Category category = categoryMapper.getById(dish.getCategoryId());
                DishVO.setCategoryName(category.getName());

                p.add(DishVO);
            }
        });
        p.setTotal(dishLists.getTotal());

        long end = System.currentTimeMillis();

        log.info("这样查询的时间：{}ms",end-start);
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 标答给的分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult getDishPage1(DishPageQueryDTO dishPageQueryDTO) {
        long start = System.currentTimeMillis();

        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);//后绪步骤实现
        long end = System.currentTimeMillis();
        log.info("本次用时{}ms",end-start);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    @Transactional//事务注解 保证数据库的一致性
    public void deleteBach(List<Long> ids) {
        int count = ids.size();//原来想删除的菜品的个数
        log.info("id的值是:{}",ids);


        //判断想要批量删除的菜品是否有在卖状态，若有，则不能删
        List<Dish> dishList = dishMapper.selectByidsIfOnSale(ids);
        if (dishList.size()!=count){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断删除菜品是否在套餐里，若有也不能删除
        List<SetmealDish> setmealDishList=setmealDishMapper.selectSetmealDish(ids);
        if (!setmealDishList.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //现在来删除dish表里面的数据
        dishMapper.deleteByids(ids);
        //并且要关联删除口味表里面dish_id对应的
        dishFlavorMapper.deleteByDishId(ids);
    }

    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO=dishMapper.selectById(id);
        List<DishFlavor> flavors=dishFlavorMapper.selectByDishId(id);


        dishVO.setFlavors(flavors);
        log.info("口味：{}",dishVO.getFlavors());
        return dishVO;

    }

    @Override
    public Dish[] getDishListBycategoryId(Long categoryId) {
        Dish[] dish=dishMapper.SelectDishListBycategoryId(categoryId);
        return dish;
    }

    /**
     * 更新菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);
        if (!dishDTO.getFlavors().isEmpty()){
            //先把对应dishId的口味都删除了
            dishFlavorMapper.deleteByDishId(Collections.singletonList(dishDTO.getId()));

            //再来挨个添加
            dishDTO.getFlavors().forEach(
                    new Consumer<DishFlavor>() {
                        @Override
                        public void accept(DishFlavor dishFlavor) {
                            dishFlavor.setDishId(dishDTO.getId());
                            dishFlavorMapper.insertWithId(dishFlavor);

                        }
                    }
            );
        }



    }

    @Override
    public void setStatus(Integer status, Long id) {
        Dish dish=new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.setStatus(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
